
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mysql.jdbc.Connection;
import lombok.SneakyThrows;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/message/list2")
public class MessageListServlet2 extends HttpServlet {
    @SneakyThrows
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 查询数据库中的表白列表
        List<Message> list = new ArrayList<>();
        // 1.得到 connection
        Connection connection = DBUtils.getConnection();
        // 2.拼接SQL，创建执行器
        String sql = "select * from messages";
        PreparedStatement statement = connection.prepareStatement(sql);
        // 3.执行SQL，返回 resultSet 并循环将数据添加到 list 中
        ResultSet resultSet = statement.executeQuery();
        while (resultSet.next()) {
            String from = resultSet.getString("from");
            String to = resultSet.getString("to");
            String message = resultSet.getString("message");
            list.add(new Message(from, to, message));
        }
        // 4.关闭资源
        DBUtils.close(resultSet, statement, connection);
        resp.setContentType("application/json; charset=utf-8");
        ObjectMapper objectMapper = new ObjectMapper();
        resp.getWriter().println(objectMapper.writeValueAsString(list));
    }
}
